package com.oalam.bookstore.domain.accounts;

import com.oalam.bookstore.dao.AccountDao;
import com.oalam.bookstore.dao.DaoFactory;
import com.oalam.bookstore.dao.FileAccountDao;
import com.oalam.bookstore.dao.FileDaoFactory;
import com.oalam.bookstore.dao.MockDaoFactory;
import com.oalam.bookstore.utils.EmailValidator;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Administrateur
 * @version 1.0
 * @created 28-juil.-2011 16:18:24
 */
public class AccountManager {

    private AccountDao dao;

    private AccountManager() {
        setupDao(false);
    }

    private static class SingletonHolder {

        private final static AccountManager instance = new AccountManager();
    }

    public static AccountManager getInstance() {
        return SingletonHolder.instance;
    }

    public final void setupDao(boolean doUseMockDao) {
        DaoFactory daoFactory = null;
        if (doUseMockDao) {
            daoFactory = new MockDaoFactory();
        } else {
            daoFactory = new FileDaoFactory();
        }

        dao = daoFactory.createAccountDao();
    }

    /**
     * 
     * @param name
     * @param address    address
     */
    public Account createAccount(String email, String pwd, String name) throws AccountCreationException {
        Account a = new Account(email, pwd, name);
        if (dao.find(a)) {
            a = null;
            throw new AccountCreationException("Account Allready exists");
        }

        dao.save(a);

        return a;
    }

    public Account getAccount(String email)  {
        Account a = new Account(email);

        if (dao.find(a)) {
            dao.load(a);
        } else {
            a = null;
           
        }

        return a;

    }

    public Account login(String email, String pwd) throws AccountLoginException, AccountLookupException {
        Account a = getAccount(email);

        if (a == null || !a.checkPassword(pwd)) {
            throw new AccountLoginException("bad password");
        }

        return a;
    }

    public void deleteAllAccount() {
        dao.deleteAll();
    }

    /**
     * 
     * @param query    query
     */
    public boolean validateQuery(String email, String pwd, String pwd2, String name) throws AccountLookupException {
        Account a = null;

        a = getAccount(email);


        return (a == null) && pwd.equals(pwd2) && EmailValidator.validate(email);
    }
}